import { _decorator, Component, Node, instantiate, Prefab, tween, Vec3 } from 'cc';
import { NodeMovementController } from './NodeMovementController';
const { ccclass, property } = _decorator;

@ccclass('CoinCollectionEffect')
export class CoinCollectionEffect extends Component {

    @property(Node)
    coinSource: Node | null = null; // 金币来源位置
    
    @property(Node)
    coinTarget: Node | null = null; // 金币收集目标位置
    
    @property(Node)
    coinPrefab: Node | null = null; // 金币预制体
    
    @property
    coinCount: number = 10; // 金币数量
    
    @property
    spawnRadius: number = 2; // 金币生成半径
    
    private parabolaSystem: NodeMovementController | null = null;
    private coins: Node[] = [];
    
    onLoad() {
        // 创建抛物线系统
        const systemNode = new Node('ParabolaSystem');
        this.node.addChild(systemNode);
        this.parabolaSystem = systemNode.addComponent(NodeMovementController);
        
        // 设置起点和终点
        this.parabolaSystem.startPos = this.coinSource.position.clone();
        this.parabolaSystem.endPos = this.coinTarget.position.clone();
        this.parabolaSystem.height = 3;
        this.parabolaSystem.duration = 1.5;
        this.parabolaSystem.delayBetween = 0.1;

        this.playCoinCollection();
    }
    
    playCoinCollection() {
        // 清除旧金币
        // this.clearCoins();
        
        // 生成新金币
        for (let i = 0; i < this.coinCount; i++) {
            const coin = instantiate(this.coinPrefab);
            this.node.addChild(coin);
            
            // 随机位置
            const angle = Math.random() * Math.PI * 2;
            const radius = Math.random() * this.spawnRadius;
            const offset = new Vec3(
                Math.cos(angle) * radius,
                Math.sin(angle) * radius,
                0
            );
            
            coin.position = this.coinSource.position.clone().add(offset);
            this.coins.push(coin);
            
            // 添加金币动画
            tween(coin)
                .to(0.3, { scale: new Vec3(1.2, 1.2, 1) })
                .to(0.2, { scale: Vec3.ONE })
                .start();
        }
        
        // 添加到抛物线系统
        this.parabolaSystem.movingNodes = this.coins;
        this.parabolaSystem.playParabolaAnimation();
    }
    
    clearCoins() {
        this.coins.forEach(coin => coin.destroy());
        this.coins = [];
    }
}
